#include "environment_variable_provider.h"
#include <QProcessEnvironment>

namespace infrastructure {

EnvironmentVariableProvider::EnvironmentVariableProvider(int priority)
    : m_priority(priority)
    , m_transformKeys(true) {
}

EnvironmentVariableProvider::EnvironmentVariableProvider(const QString& prefix, int priority)
    : m_prefix(prefix)
    , m_priority(priority)
    , m_transformKeys(true) {
}

EnvironmentVariableProvider::EnvironmentVariableProvider(const QStringList& allowedKeys, int priority)
    : m_allowedKeys(allowedKeys)
    , m_priority(priority)
    , m_transformKeys(true) {
}

ConfigurationData EnvironmentVariableProvider::load() {
    ConfigurationData result;
    
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    QStringList envKeys = env.keys();
    
    for (const QString& envKey : envKeys) {
        // 检查键是否被允许
        if (!isKeyAllowed(envKey)) {
            continue;
        }
        
        // 应用前缀过滤
        if (!m_prefix.isEmpty() && !envKey.startsWith(m_prefix)) {
            continue;
        }
        
        // 获取环境变量值
        QString envValue = env.value(envKey);
        if (envValue.isEmpty()) {
            continue;
        }
        
        // 转换键名格式
        QString configKey = transformKey(envKey);
        if (configKey.isEmpty()) {
            continue;
        }
        
        result.values[configKey] = envValue;
    }
    
    return result;
}

bool EnvironmentVariableProvider::isAvailable() const {
    return true;
}

QString EnvironmentVariableProvider::getDescription() const {
    QString desc = "环境变量配置提供者";
    
    if (!m_prefix.isEmpty()) {
        desc += QString(" (前缀: %1)").arg(m_prefix);
    }
    
    if (!m_allowedKeys.isEmpty()) {
        desc += QString(" (允许的键: %1个)").arg(m_allowedKeys.size());
    }
    
    return desc;
}

void EnvironmentVariableProvider::setChangeCallback(ConfigurationChangeCallback callback) {
    m_callback = callback;
}

void EnvironmentVariableProvider::startWatching() {
}

void EnvironmentVariableProvider::stopWatching() {
}

int EnvironmentVariableProvider::getPriority() const {
    return m_priority;
}

QString EnvironmentVariableProvider::transformKey(const QString& envKey) const {
    if (!m_transformKeys) {
        return envKey;
    }
    
    QString result = envKey;
    
    // 移除前缀
    if (!m_prefix.isEmpty() && result.startsWith(m_prefix)) {
        result = result.mid(m_prefix.length());
        
        // 移除前缀后的分隔符
        if (result.startsWith("_") || result.startsWith("-")) {
            result = result.mid(1);
        }
    }
    
    // 转换为小写
    result = result.toLower();
    
    // 将下划线转换为冒号（用于分层配置）
    result.replace("_", ":");
    
    // 将双划线转换为下划线（转义）
    result.replace("--", "_");
    
    return result;
}

bool EnvironmentVariableProvider::isKeyAllowed(const QString& envKey) const {
    // 如果没有设置允许列表，则允许所有键
    if (m_allowedKeys.isEmpty()) {
        return true;
    }
    
    // 检查键是否在允许列表中
    for (const QString& allowedKey : m_allowedKeys) {
        if (envKey == allowedKey) {
            return true;
        }
        
        // 支持通配符匹配
        if (allowedKey.contains("*")) {
            QRegularExpression regex(QRegularExpression::wildcardToRegularExpression(allowedKey));
            if (regex.match(envKey).hasMatch()) {
                return true;
            }
        }
    }
    
    return false;
}

QString EnvironmentVariableProvider::getEnvironmentValue(const QString& key) const {
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    return env.value(key);
}

} // namespace infrastructure 